<?php
error_reporting('IGNORE_REPEATED_ERRORS');
$debug = 0;

function test_print($item, $key)
{
    echo "$key holds $item<BR>\r\n";
}


$document = $_POST["document"];
$iavedata = $_POST["iavedata"];



/**********************************
 * Display input form
 **********************************/

if ((strlen($document)<1) && (strlen($iavedata)<1)) {
	echo "<html>";
	echo "<HEAD>";
	echo "</HEAD>";
	echo "<body>";
	echo "<form name=\"report_form\" id=\"report_form\" action=\"process.php\" method=\"post\">";
	echo "Cut and Paste Document to process here:<BR>";
	echo "<textarea name=\"document\" id=\"document\" rows=20 cols=80 value=\"\"></textarea><BR>";
	echo "Open document, select all, copy.  Then paste into the above form.<BR><BR>";
	echo "Cut and Paste iAve CSV fields here:<BR>";
	echo "<textarea name=\"iavedata\" id=\"data\" rows=20 cols=80 value=\"\"></textarea><BR>";
	echo "Open iAve data as CSV, select all, copy and then paste in the space.<BR>";
	echo "Fields: CNTCT_LST_NM,CNTCT_FRST_NM,CNTCT_ADRS1_TXT,CNTCT_ADRS2_TXT,CNTCT_CTY_NM,ZIP_CD,DY_PHN_AREA_CD,DY_PHN_NBR,NIT_PHN_AREA_CD,NIT_PHN_NBR,E_MAIL_ADRS_TXT<BR><BR>";
	echo "<input type=\"reset\" value=\"Reset\"/> <BR>";
	echo "<input type=\"submit\" value=\"Process\"/> <BR>";
	echo "<br>";
	echo "</body>";
	echo "</html>";
}


/**********************************
 * Process input
 **********************************/

if ( (strlen($document)>0) && (strlen($iavedata)>0) ) {

	
	$renewal = array();
	$line = array();

	
	/**********************************
	 * Process Renewal Document
	 **********************************/

	$matches = split("\t", $document);
	$last = "";
	foreach($matches as $item){
		$item = trim($item);

			switch ($last){
				case 'MEMBER:':
					$line["MEMBER"] = $item;
					break;
				case 'NAME:':
					$line["NAME"] = $item;
					break;
				case 'AGE:':
					$line["AGE"] = $item;
					break;
				case 'SEX:':
					$line["SEX"] = $item;
					break;
				case 'COUNTY:':
					$line["COUNTY"] = $item;
					break;
				case 'HCID:':
					$line["HCID"] = $item;
					break;
				case 'PHONE:':
					$line["PHONE"] = $item;
					break;
				case 'CURRENT GRP:':
					if( preg_match("/,/",$item) ){
						$line["CURRENT GRP"] = $item;
					}else{
						$line["CURRENT GRP"] = $item;
					}
					break;
				case 'Rate:':
					$line["RATE"] = $item;
					break;
				case 'OPTION 1:':
					$renewal_count = 1;
					break;
			}

			if($renewal_count==3){
				$line["OPTION 1"] = $item."\r\n";
				$renewal_count=0;
			}elseif($renewal_count>0){
				$renewal_count = $renewal_count + 1;
			}

		$last = $item;


		$renewal[$line["NAME"]]=$line;
	}



	/**********************************
	 * Process iAve Data
	 **********************************/

	$iave = array();
	$line = array();
	$i = 0;
	//echo "<HTML><HEAD/><BODY>\r\n";
	$iavelines = split("\r\n",$iavedata);
	foreach($iavelines as $currentline){
		$splitline = split(",", $currentline);
		if ($i > 0){//discard header
			$line["NAME"] = strtoupper($splitline[0].",".$splitline[1]);
			$line["STREET"] = $splitline[2]."\r\n".$splitline[3];
			$line["PHONE_DAY"] = "(".$splitline[6].") ".substr($splitline[7],0,3)."-".substr($splitline[7],3,7);
			$line["PHONE_NIGHT"] = "(".$splitline[8].") ".substr($splitline[9],0,3)."-".substr($splitline[9],3,7);
			$line["CITY"] = $splitline[4];
			$line["ZIP"] = $splitline[5];
			$line["EMAIL"] = $splitline[10];
			if($debug){array_walk($line, 'test_print');}
			$iave[$line["NAME"]] = $line;
		}
		if($splitline[0]=="CNTCT_LST_NM"){$i = 1;} //check for header
	}



	/**********************************
	 * Merge Results
	 **********************************/

	$results = array();
	$matches = 0;
	$misses = 0;


	foreach($renewal as $working){
		if(array_key_exists($working["NAME"],$iave)){
			$results[$working["NAME"]] = array_merge($working, $iave[$working["NAME"]], array("EXCEPTION" => 0, "OTHER_NAME" => ""));
			$matches++;
		}else{

			$phone = $working["PHONE"];
			$temp_array = array();
			$phone_found = 0;
			foreach ($iave as $search){
				if ( ($phone == $search["PHONE_DAY"]) || ($phone == $search["PHONE_NIGHT"]) ){
					$search["OTHER_NAME"] = $search["NAME"];
					unset($search["NAME"]);
					$results[$working["NAME"]] = array_merge($search, $working, array("EXCEPTION" => 0));
					$phone_found = 1;
					break;
				}
			}
			
			if($phone_found == 0){
				$results[$working["NAME"]] = array_merge($working, array("EXCEPTION" => 1));
				$misses++;
			}
		}
	}




	/**********************************
	 * Output Results
	 **********************************/

	if($debug){
		echo "<HTML><HEAD/><BODY>\r\n";
		echo "matches: $matches<BR>";
		echo "misses: $misses<BR>";
		echo "renewal size: ".count($renewal)."<BR>";
		echo "iave size: ".count($iave)." <BR>";
		echo "</BODY></HTML>\r\n";
	}

	header('Content-type: application/excel');
	header('Content-Disposition: attachment; filename="results.csv"');

	$exceptions = "";
	$exception_keys = array();
	$value = "";
	$header=1;
	$result_keys = array_keys($results);
	foreach($result_keys as $renewal_name){
		if(strlen($renewal_name)>0){ 
			$temp_arr = array();
			$temp_arr = $results[$renewal_name]; 
			ksort($temp_arr);
			if($header){
				$header_values = array();
				$header_values = array_keys($temp_arr);
				foreach($header_values as $value){
					$outbuf .= trim($value).",";
				}
				echo trim($outbuf,",")."\r\n";
				$outbuf = "";
				$value = "";
				$header--;
			}
			if($temp_arr["EXCEPTION"] == 1){
				if(count($exception_keys)==0){
					$exception_keys = array_keys($temp_arr);
				}
				foreach($temp_arr as $value){
					$outbuf .= trim($value).",";
				}
				$exceptions .= trim($outbuf,",")."\r\n";
				$outbuf = "";
			}else{
				foreach($temp_arr as $value){
					$outbuf .= trim($value).",";
				}
				echo trim($outbuf,",")."\r\n";
				$outbuf = "";
				$value = "";
			}
		}
	}
	echo "\r\n\r\n";
	foreach($exception_keys as $value){
		$outbuf .= trim($value).",";
	}
	echo trim($outbuf,",")."\r\n";
	echo $exceptions;


}




?>
